package com.csyaonie.android.storage;

import androidx.appcompat.app.AppCompatActivity;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.csyaonie.android.R;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileActivity extends AppCompatActivity {

    private EditText sEditText;
    private Button sSave;
    private Button sShow;
    private TextView sTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_file);
        sEditText=findViewById(R.id.sEditText);
        sSave=findViewById(R.id.sSave);
        sShow=findViewById(R.id.sShow);
        sTextView=findViewById(R.id.sTextView);


        sSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                save(sEditText.getText().toString());
            }
        });

        sShow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sTextView.setText(read());
            }
        });

    }

    private void save(String content){
        FileOutputStream fos=null;
        try {
            fos=openFileOutput("test",MODE_PRIVATE);
            fos.write(sEditText.getText().toString().getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(null!=fos){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private String read(){
        FileInputStream fis=null;
        try {
            fis=openFileInput("test");
            byte[] buff=new byte[1024];
            int len=0;
            StringBuilder sb=new StringBuilder();
            while ((len=fis.read(buff))>0){
                sb.append(new String(buff,0,len));
            }
            return sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(null!=fis){
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

}